package cn.sangyy.basic.service.impl;

import cn.sangyy.basic.service.ICosService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author SangYY
 * @date: 2023/05/24/17:11
 */
@Service
public class CosServiceImpl implements ICosService {

    @Value("${TxCos.bucketName}")
    private String bucketName;
    @Value("${TxCos.region}")
    private String region;
    @Value("${TxCos.appId}")
    private String appId;
    @Value("${TxCos.secretId}")
    private String secretId;
    @Value("${TxCos.secretKey}")
    private String secretKey;
    @Value("${TxCos.domainName}")
    private String domainName;


    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        //这是bucket区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        //生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        //设置线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(16);
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        UUID uuid = UUID.randomUUID();
        String filename = file.getOriginalFilename();
        assert filename != null;
        String prefix = filename.substring(filename.lastIndexOf("."));
        File newFile = File.createTempFile(filename, prefix);
        file.transferTo(newFile);
        String key = "images/rcb/"+uuid+"_"+filename;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, newFile);
        Upload upload = transferManager.upload(putObjectRequest);
        upload.waitForCompletion();
        Date date = new Date(new Date().getTime() + 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, key, date);
        String path = domainName+url.getPath();
        return path;
    }

    @Override
    public void deleteImage(String path) {
        BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        //这是bucket区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        //生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        String key = path.substring(domainName.length() + 1);
        cosClient.deleteObject(bucketName,key);
    }
}
